<template>
    <div>
        <div class="flex justify-end mb-2">
            <button
                class="px-4 py-1 m-2
                    text-purple-600 font-semibold
                    rounded-full border border-purple-200
                    enabled:hover:text-white enabled:hover:bg-purple-600
                    disabled:cursor-not-allowed disabled:opacity-60"
                    :data-te-target="allowHomeworkModify?'':'tooltip'"
                    :title="allowHomeworkModify?'':'only teacher can add homework'"
                    :disabled="!allowHomeworkModify"
                @click="dialogAddHomeworkVisible=true"
            >
                ADD Homework
            </button>
        </div>
        <div class="grid grid-cols-1 divide-y-8 divide-blue-200 space-y-3">
            <div class="border rounded border-slate-300 divide-y"
                    v-for="homework in homeworkList"
                    :key="homework._id"
            >
                <div>
                    <div class="flex justify-start">
                        <span class="mx-3 mt-3 text-xl">
                            {{ homework.name }}
                        </span>
                    </div>
                    <div class="flex justify-end space-x-5 m-2">
                        <button
                            @click="dialogCheckHomeworkVisible=true, currentHomework=homework"
                            class="px-2 py-1 m-2
                                text-purple-600 font-semibold
                                rounded border border-purple-200
                                enabled:hover:text-white enabled:hover:bg-purple-600
                                disabled:cursor-not-allowed disabled:opacity-70"
                        >
                            show
                        </button>
                        <button
                            @click="dialogUpdateHomeworkVisible=true, currentHomework=homework"
                            class="px-2 py-1 m-2
                                text-purple-600 font-semibold
                                rounded border border-purple-200
                                enabled:hover:text-white enabled:hover:bg-purple-600
                                disabled:cursor-not-allowed disabled:opacity-70"
                                :data-te-target="allowHomeworkModify?'':'tooltip'"
                                :title="allowHomeworkModify?'':'only creator of the course can modify homework content'"
                                :disabled="!allowHomeworkModify"
                        >
                            modify
                        </button>
                        <button 
                            @click="dialogSubmitReportVisible=true, currentHomework=homework"
                            class="px-2 py-1 m-2
                                text-purple-600 font-semibold
                                rounded border border-purple-200
                                enabled:hover:text-white enabled:hover:bg-purple-600
                                disabled:cursor-not-allowed disabled:opacity-70"
                        >
                            submit
                        </button>
                        <button
                            @click="toggleScoreList" :value="homework._id"
                            class="px-2 py-1 m-2
                                text-purple-600 font-semibold
                                rounded border border-purple-200
                                enabled:hover:text-white enabled:hover:bg-purple-600
                                disabled:cursor-not-allowed disabled:opacity-70"
                        >
                            score
                        </button>
                    </div>
                </div>
                <div v-if="currentTableHomeworkId == homework._id">
                    <table class="table-auto">
                        <thead>
                            <tr>
                                <th class="px-8 py-2">student name</th>
                                <th class="px-8 py-2">report</th>
                                <th class="px-8 py-2">score</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="report in reports" :key="report._id">
                                <td class="px-8 py-2">{{ report.uploader.username }}</td>
                                <td v-if="report._id"
                                    class="px-8 py-2"
                                >
                                    <button
                                    @click="dialogScoreReportVisible=true, currentReport=report"
                                    class="enabled:cursor-pointer disabled:cursor-not-allowed"
                                    :data-te-target="allowReportScore?'':'tooltip'"
                                    :title="allowReportScore?'':'only ta or teacher can see others report'"
                                    :disabled="!allowReportScore"
                                    >
                                        &#9989;
                                    </button>
                                </td>
                                <td v-else class="px-8 py-2">-</td>
                                <td class="px-8 py-2">{{ report.score }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!--add homework dialog-->
        <el-dialog v-model="dialogAddHomeworkVisible">
            <h2 class="bold text-3xl font-sans leading-8">Add new homework</h2>
            <div class="">
                <input
                    type="text"
                    class="form-control block w-full"
                    v-model="newHomeworkName"
                    placeholder="homework name"
                />
            </div>
            <div class="">
                <mavon-editor v-model="newHomeworkContent"></mavon-editor>
            </div>
            <div>
                <button
                    class="rounded-full border justify-self-start"
                    @click="onSaveNewHomework"
                >
                    save
                </button>
            </div>
        </el-dialog>

        <!--update homework dialog-->
        <el-dialog v-model="dialogUpdateHomeworkVisible">
            <div class="space-y-5">
                <div class="">
                    <input
                        type="text"
                        class="form-control block w-full"
                        v-model="currentHomework.name"
                        placeholder="homework name"
                    />
                </div>
                <div class="">
                    <mavon-editor v-model="currentHomework.content"></mavon-editor>
                </div>
                <div>
                    <button
                        class="border rounded px-2 py-1 bg-sky-400 text-white"
                        @click="onUpdateHomework"
                    >
                        save
                    </button>
                </div>
            </div>
        </el-dialog>

        <!--submit report dialog-->
        <el-dialog v-model="dialogSubmitReportVisible">
            <div class="">
                <mavon-editor v-model="currentReport"></mavon-editor>
            </div>
            <div>
                <button
                    class="border rounded px-2 py-1 bg-sky-400 text-white"
                    @click="onSubmitReport"
                >
                    save
                </button>
            </div>
        </el-dialog>

        <!--check homework dialog-->
        <el-dialog v-model="dialogCheckHomeworkVisible">
            <div class="divide-y">
                <h1 class="text-2xl">{{ currentHomework.name }}</h1>
                <v-md-preview :text="currentHomework.content"></v-md-preview>
            </div>
        </el-dialog>

        <!--score report dialog-->
        <el-dialog v-model="dialogScoreReportVisible">
            <div class="space-y-6">
                <div>
                    <v-md-preview :text="currentReport.content"></v-md-preview>
                </div>
                <div>
                    <span class="px-2 text-lg">score</span>
                    <input type="text" class="border rounded px-2 py-1" v-model="currentReport.score" />
                </div>
                <div>
                    <button
                        @click="onScoreReport"
                        class="border rounded px-2 py-1 bg-sky-400 text-white"
                    >
                        submit
                    </button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import HomeworkService from '@/services/HomeworkService.js';
import AC from '@/accesscontrol.js';

export default {
    name: 'HomeworkList',
    components: {
    },
    data() {
        return {
            newHomeworkName: '',
            newHomeworkContent: '',
            homeworkList: [],
            currentHomework: '',  // object
            currentReport: '',
            reports: '',  // list of report object of current homework
            dialogAddHomeworkVisible: false,
            dialogUpdateHomeworkVisible: false,
            dialogSubmitReportVisible: false,
            dialogCheckHomeworkVisible: false,
            dialogScoreReportVisible: false,
            currentTableHomeworkId: '',  // determine showing table
        }
    },
    computed: {
        allowHomeworkModify() {
            if(!this.$store.state.user.role) return false;
            const permission = AC.can(this.$store.state.user.role).updateAny('homework');
            const permission2 = AC.can(this.$store.state.user.role).updateOwn('homework');
            return permission.granted ||
                (permission2.granted && this.courseInfo.creator == this.$store.state.user.id);
        },
        allowReportScore() {
            if(!this.$store.state.user.role) return false;
            const permission = AC.can(this.$store.state.user.role).updateAny('score');
            const permission2 = AC.can(this.$store.state.user.role).updateOwn('score');
            return permission.granted ||
                (permission2.granted);
        },
    },
    watch: {
        courseInfo(newCourseInfo, oldCourseInfo) {
            console.log('find courseInfo changed');
            if(newCourseInfo._id) {
                this.getHomeworkList();
            }
        },
    },
    props: {
        courseInfo: '',
    },
    created() {
        this.getHomeworkList();
    },
    methods: {
        async getHomeworkList() {
            if(!this.courseInfo._id) return;
            console.log('courseInfo', this.courseInfo);
            const res = await HomeworkService.getHomework({course: this.courseInfo._id});
            this.homeworkList = res.data.homework;
            console.log("get homework list:", res);
        },
        async onSaveNewHomework() {
          if(!this.$store.state.user.id) {
              this.$message.error("Please login first");
              return;
          }
          try {
              const res = await HomeworkService.addHomework({
                  name: this.newHomeworkName,
                  content: this.newHomeworkContent,
                  course: this.courseInfo._id,
                  uploader: this.$store.state.user.id,
              });
              this.$message.success("add homework successfully");
              console.log("onSaveNewHomework: ", res);
              await this.getHomeworkList(); // refresh homeworklist
              this.dialogAddHomeworkVisible = 0;
          } catch(e) {
              console.log("ERROR onSaveNewHomework: ", e);
              this.$message.error("failed to add new homework");
          }
        },
        async onUpdateHomework() {
          if(!this.$store.state.user.id) {
              this.$message.error("Please login first");
              return;
          }
          try {
              const res = await HomeworkService.addHomework({
                  name: this.currentHomework.name,
                  content: this.currentHomework.content,
                  course: this.courseInfo._id,
                  uploader: this.$store.state.user.id,
              });
              this.$message.success("update homework successfully");
              await this.getHomeworkList(); // refresh homeworklist
              this.dialogUpdateHomeworkVisible = 0;
          } catch(e) {
              console.log("ERROR onUpdateHomework: ", e);
              this.$message.error("failed to update homework");
          }
        },
        async toggleScoreList(params) {
            // toggle current table
            if (this.currentTableHomeworkId == params.target.value) {
                this.currentTableHomeworkId = '';
                return;
            }
            this.currentTableHomeworkId = params.target.value;
            const res = await HomeworkService.getReportsByHomeworkId({
                id: this.currentTableHomeworkId,
            });
            this.reports = res.data;
        },
        async onSubmitReport() {
            if(!this.$store.state.user.id) {
                this.$message.error("Please login first");
                return;
            }
            try {
                const res = await HomeworkService.submitHomework({
                    name: this.currentHomework.name,
                    course: this.currentHomework.course,
                    content: this.currentReport,
                    uploader: this.$store.state.user.id,
                })
                this.$message.success("submit report successfully");
            } catch(e) {
                console.log(e);
                this.$message.error("failed to submit report");
            }
        },
        async onScoreReport() {
            try {
                const res = await HomeworkService.scoreHomework({
                    id: this.currentReport._id,
                    score: this.currentReport.score,
                })
                this.$message.success("score report successfully");
            } catch(e) {
                console.log(e);
                this.$message.error("failed to score report");
            }
        },
    },
}
</script>
